package com.dongdongshop.shiro;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.exception.LoginException;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.service.SellerService;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;

public class LoginRealm extends AuthorizingRealm {
    @Reference
    private SellerService sellerService;
    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        System.out.println("进入授权方法");
//        TbSeller tbSeller = (TbSeller) SecurityUtils.getSubject().getPrincipal();
//        //查询菜单权限
//        List<String> perms = sellerService.selectPermsByUserId(TbSeller.getPid());
//        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermissions(perms);

//        return info;
        return null;
    }

    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进入认证方法");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        TbSeller tbSeller = sellerService.selectByTperson(username);
        if (tbSeller == null){
            return null;
        }

        if (!tbSeller.getStatus().equals("1")){
            throw new LoginException("未审核");
        }
        //第一个参数 是登录成功后需要放入sessin的对象
        //第二个参数 是数据库查询出来的密码
        //第三个参数 是用户的名字（账号）
        return new SimpleAuthenticationInfo(tbSeller,tbSeller.getPassword(), ByteSource.Util.bytes(tbSeller.getSalt()),tbSeller.getSellerId());
    }

}
